package com.example.designpatternproject.builder;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;

/**
 * @ClassName: BaseNavigationBar
 * @Author: 史大拿
 * @CreateDate: 10/18/22$ 2:23 PM$
 * TODO
 */
public class BaseNavigationBar implements INavigationBar {

    private final Builder<?> mBuilder;

    public BaseNavigationBar(Builder<?> builder) {
        mBuilder = builder;

        // 绑定参数
        attachParams(builder.mContext, builder.mView, builder.mParent);

    }

    protected <T extends View> T findViewById(@IdRes int id) {
        return mBuilder.findViewById(id);
    }

    @Override
    public void attachParams(Context context, View view, ViewGroup parent) {
        // 添加View
        parent.addView(view);
    }

    public abstract static class Builder<E extends INavigationBar> {

        private final Context mContext;
        private final View mView;
        private final ViewGroup mParent;

        public Builder(Context context, @LayoutRes int layoutId, ViewGroup parent) {
            this.mContext = context;
            this.mParent = parent;
            mView = LayoutInflater.from(mContext).inflate(layoutId, parent, false);
        }

        protected <T extends View> T findViewById(@IdRes int id) {
            return mView.findViewById(id);
        }

        public Builder<E> setText(@IdRes int id, String msg) {
            View tv = findViewById(id);
            if (tv instanceof TextView) {
                ((TextView) tv).setText(msg);
            }
            return (Builder<E>) this;
        }

        public Builder<E> setVisibility(@IdRes int id, int visibility) {
            View tv = findViewById(id);
            tv.setVisibility(visibility);
            return (Builder<E>) this;
        }

        public Builder<E> setOnClickListener(@IdRes int id, View.OnClickListener clickListener) {
            View view = findViewById(id);
            if (view != null) {
                view.setOnClickListener(clickListener);
            }
            return (Builder<E>) this;
        }

        protected void showToast(@NonNull Object msg) {
            Toast.makeText(mContext, msg.toString(), Toast.LENGTH_SHORT).show();
        }

        abstract E builder();
    }
}
